<template>
  <view class="evaluate-container">
    <view class="nav-header">
      <view class="nav-back" @click="goBack"><text class="back-icon">←</text></view>
      <text class="nav-title">医生评价</text>
      <view class="nav-right"></view>
    </view>

    <view class="content" :style="{ paddingTop: '88rpx' }">
      <!-- 医生信息 -->
      <view class="doctor-card">
        <image class="doctor-avatar" :src="doctorAvatarFinal" mode="aspectFill" />
        <view class="doctor-meta">
          <text class="doctor-name">{{ doctorName || '医生' }}</text>
          <text class="doctor-id">ID: {{ doctorId }}</text>
        </view>
      </view>

      <!-- 星级评分 -->
      <view class="rating-block">
        <text class="label">服务评分</text>
        <view class="stars">
          <text
            v-for="i in 5"
            :key="i"
            class="star"
            :class="{ active: i <= score }"
            @click="setScore(i)">★</text>
        </view>
        <text class="score-text">{{ score }} 分</text>
      </view>

      <!-- 文字评价 -->
      <view class="textarea-block">
        <textarea
          v-model="content"
          class="textarea"
          placeholder="请描述本次问诊体验（不少于5个字）"
          maxlength="500"
          auto-height
        />
        <text class="count">{{ content.length }}/500</text>
      </view>

      <!-- 图片上传 -->
      <view class="images-section">
        <view class="header-row">
          <text class="label">上传图片（可选，最多6张）</text>
          <text class="tip">支持 jpg/png</text>
        </view>
        <view class="images-grid">
          <view class="img-item" v-for="(url, idx) in imageList" :key="idx">
            <image class="img" :src="url" mode="aspectFill" @click="preview(url)" />
            <view class="close" @click="remove(idx)">×</view>
          </view>
          <view v-if="imageList.length < 6" class="img-item upload" @click="chooseAndUpload">
            <text class="plus">＋</text>
          </view>
        </view>
      </view>

      <view class="btn-area">
        <button class="btn" type="primary" :disabled="submitting" @click="submit">
          {{ submitting ? '提交中...' : '提交评价' }}
        </button>
      </view>
    </view>
  </view>
</template>

<script>
import { submitEvaluation, checkEvaluationAllowed } from '@/api/patientEvaluation.js'
import upload from '@/utils/upload'

export default {
  data() {
    return {
      doctorId: null,
      doctorName: '',
      doctorAvatar: '',
      score: 5,
      content: '',
      imageList: [],
      submitting: false,
    }
  },
  computed: {
    doctorAvatarFinal() {
      return this.doctorAvatar || '/static/dayi.png'
    }
  },
  onLoad(options) {
    if (options && options.doctorId) this.doctorId = Number(options.doctorId)
    if (options && options.doctorName) this.doctorName = decodeURIComponent(options.doctorName)
    if (options && options.doctorAvatar) this.doctorAvatar = decodeURIComponent(options.doctorAvatar)

    // 可选：进入页时检查是否允许评价
    if (this.doctorId) {
      checkEvaluationAllowed(this.doctorId).then(res => {
        if (res && res.code === 200 && res.data === false) {
          uni.showToast({ title: '暂不可评价', icon: 'none' })
          setTimeout(() => uni.navigateBack(), 1200)
        }
      }).catch(() => {})
    }
  },
  methods: {
    goBack() { uni.navigateBack() },
    setScore(i) { this.score = i },
    preview(url) { uni.previewImage({ urls: [url] }) },
    remove(idx) { this.imageList.splice(idx, 1) },
    async chooseAndUpload() {
      try {
        const chooseRes = await new Promise((resolve, reject) => {
          uni.chooseImage({
            count: Math.min(6 - this.imageList.length, 6),
            sizeType: ['compressed'],
            sourceType: ['album', 'camera'],
            success: resolve,
            fail: reject
          })
        })
        const files = chooseRes.tempFilePaths || []
        for (const path of files) {
          const url = await this.uploadFile(path)
          if (url) this.imageList.push(url)
        }
      } catch (e) {
        uni.showToast({ title: '选择图片失败', icon: 'none' })
      }
    },
    async uploadFile(filePath) {
      // 切换为网关文件服务上传：/file/upload，复用统一上传封装
      try {
        const result = await upload({ url: '/file/upload', filePath, name: 'file' })
        // 返回结构：{ code:200, data:{ url, name }, msg }
        const url = result && result.data && result.data.url
        if (url) return url
        // 若无URL则回退本地预览
        return filePath
      } catch (e) {
        uni.showToast({ title: '上传失败', icon: 'none' })
        return ''
      }
    },
    async submit() {
      if (!this.doctorId) {
        uni.showToast({ title: '缺少医生ID', icon: 'none' })
        return
      }
      if (!this.content || this.content.trim().length < 5) {
        uni.showToast({ title: '评价内容不少于5个字', icon: 'none' })
        return
      }
      this.submitting = true
      try {
        // 后端DTO字段：doctorId、professionalScore、serviceScore、evaluationContent（无images字段）
        const payload = {
          doctorId: this.doctorId,
          professionalScore: this.score,
          serviceScore: this.score,
          evaluationContent: this.content.trim()
        }
        const res = await submitEvaluation(payload)
        if (res && (res.code === 200 || res.success)) {
          uni.showToast({ title: '提交成功', icon: 'success' })
          setTimeout(() => uni.navigateBack(), 1000)
        } else {
          uni.showToast({ title: (res && res.msg) || '提交失败', icon: 'none' })
        }
      } catch (e) {
        uni.showToast({ title: '提交异常', icon: 'none' })
      } finally {
        this.submitting = false
      }
    }
  }
}
</script>

<style scoped>
.evaluate-container { height: 100vh; background: #f7f8fa; }
.nav-header { height: 88rpx; background: #fff; display: flex; align-items: center; justify-content: space-between; padding: 0 30rpx; border-bottom: 1px solid #e5e5e5; position: fixed; top: 0; left: 0; right: 0; z-index: 9; }
.back-icon { font-size: 32rpx; }
.nav-title { font-size: 32rpx; font-weight: 600; }

.content { padding: 24rpx; }
.doctor-card { display: flex; align-items: center; gap: 20rpx; background: #fff; padding: 20rpx; border-radius: 16rpx; }
.doctor-avatar { width: 96rpx; height: 96rpx; border-radius: 48rpx; background: #f0f0f0; }
.doctor-name { font-size: 30rpx; font-weight: 600; }
.doctor-id { font-size: 24rpx; color: #999; margin-top: 6rpx; }

.rating-block { margin-top: 20rpx; background: #fff; padding: 20rpx; border-radius: 16rpx; }
.label { font-size: 28rpx; color: #333; }
.stars { display: flex; gap: 10rpx; margin-top: 12rpx; }
.star { font-size: 40rpx; color: #ddd; }
.star.active { color: #FFD21E; }
.score-text { margin-left: 12rpx; color: #666; font-size: 26rpx; }

.textarea-block { position: relative; margin-top: 20rpx; background: #fff; padding: 12rpx; border-radius: 16rpx; }
.textarea { min-height: 160rpx; width: 100%; font-size: 28rpx; padding: 12rpx; box-sizing: border-box; }
.count { position: absolute; bottom: 16rpx; right: 20rpx; color: #999; font-size: 24rpx; }

.images-section { margin-top: 20rpx; background: #fff; padding: 20rpx; border-radius: 16rpx; }
.header-row { display: flex; justify-content: space-between; align-items: center; margin-bottom: 12rpx; }
.tip { font-size: 22rpx; color: #999; }
.images-grid { display: flex; flex-wrap: wrap; gap: 16rpx; }
.img-item { width: 200rpx; height: 200rpx; border-radius: 12rpx; overflow: hidden; position: relative; background: #f2f3f5; }
.img { width: 100%; height: 100%; }
.img-item.upload { display: flex; align-items: center; justify-content: center; border: 1px dashed #ccc; }
.plus { font-size: 60rpx; color: #bbb; }
.close { position: absolute; top: 6rpx; right: 6rpx; width: 36rpx; height: 36rpx; border-radius: 18rpx; background: rgba(0,0,0,0.6); color: #fff; display:flex; align-items:center; justify-content:center; font-size: 26rpx; }

.btn-area { margin-top: 30rpx; }
.btn { background: #007AFF; color: #fff; border-radius: 10rpx; }
</style>
